<template>
  <div class="order-preview-container">
    <div class="order-title">
      联系人信息
    </div>
    <div class="order-contact">
      <van-form ref="form" @submit="onSubmit">
        <van-field
          label="联系人"
          v-model="contact"
          name="username"
          placeholder="请输入联系人姓名"
          :rules="rules.name"
        />
        <van-field
          :label="!areaString ? '请选择地区' : ''"
          name="area"
          :value="areaString"
          right-icon="arrow"
          readonly
          :rules="rules.area"
          @click="showArea = true"/>
        <van-field
          label="地址"
          v-model="address"
          name="address"
          placeholder="请输入详细地址"
          :rules="rules.address"
        />
      </van-form>
    </div>
    <div class="order-title">
      已选产品
    </div>
    <div class="product-list">
      <ProductCell v-for="(prod) in preview.products" :product="prod" :key="prod.id"></ProductCell>
    </div>
    <div class="order-action">
      <div class="order-count">
        共{{preview.count}}件
      </div>
      <div class="order-total">
        合计：<span class="cart-price"><small>￥</small>{{preview.total}}</span>
      </div>
      <van-button class="vant-red-grd-btn order-btn" round :loading="submitting" loading-text="结算" @click="onSubmit">结算</van-button>
    </div>
    <van-popup v-model="showArea" position="bottom" :style="{ height: '308px' }">
      <van-area title="选择地区" :area-list="areaList" :columns-num="3" @cancel="onAreaCancel" @confirm="onAreaConfirm"/>
    </van-popup>
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast, Field, Button, Form, Area } from 'vant'
import validate from '@/common/validate.js'
import { areaList } from '@/common/utils/areaList.js'
// import _ from 'lodash'

import ProductCell from './components/ProductCell'

Vue.use(Toast)
Vue.use(Field)
Vue.use(Button)
Vue.use(Form)
Vue.use(Area)

const rules = {
  name: [
    { required: true, message: '请输入联系人姓名' },
    ...validate.name
  ],
  area: [
    { required: true, message: '请选择地区' }
  ],
  address: [
    { required: true, message: '请输入详细地址' },
    ...validate.address
  ]
}

export default {
  name: 'Preview',
  components: {
    ProductCell
  },
  data () {
    return {
      preview: {},
      rules: rules,
      // 联系人信息
      contact: '',
      showArea: false,
      areaList: areaList,
      areaResult: [],
      area: '',
      address: '',
      submitting: false
    }
  },
  computed: {
    areaString () {
      const areaMap = this.areaResult.map((area) => {
        return area.name
      })

      return areaMap.join(' ')
    }
  },
  created () {
    this.fetch()
  },
  methods: {
    fetch () {
      this.$api.get('/order/getPreviewOrder.action')
        .then((result) => {
          if (result) {
            this.preview = result
          }
        })
        .catch(err => this.$toast(err.message))
    },
    onAreaCancel () {
      this.showArea = false
    },
    onAreaConfirm (columnsNum) {
      this.showArea = false
      this.areaResult = columnsNum
    },
    onSubmit () {
      const { preview, contact, areaString, address } = this

      if (this.submitting) return

      this.$refs.form.validate().then(() => {
        const data = {
          products: preview.products,
          contact: {
            name: contact,
            area: areaString,
            address: address
          }
        }

        this.submitting = true

        this.$api.post('/order/submit.action', {
          data: data
        })
          .then((result) => {
            this.submitting = false
            if (result) {
              // 下单成功从购物车清空对应商品
              this.clearCart(data.products)

              this.$router.push({
                path: '/order/detail',
                query: {
                  id: result.orderId
                }
              })
            } else {
              this.$toast('下单失败，请稍后重试')
            }
          })
          .catch((err) => {
            this.submitting = false
            this.$toast(err.message)
          })
      }).catch(() => {
        this.$refs.form.scrollToField()
      })
    },
    clearCart (products) {
      this.$store.dispatch('removeSomeFromCart', products.map(prod => prod.id))
    }
  }
}
</script>

<style lang="less">
  .order-preview-container {
    padding-bottom: 76px;

    .order-contact {
      margin: 0 10px;
    }

    .order-title {
      padding: 0 10px;
      line-height: 1.8;
      color: #666666;
    }

    .product-list {
      background: #fff;
      padding: 10px 0;
      margin: 0 10px;
    }

    .order-action {
      position: fixed;
      bottom: 0;
      left: 0;
      z-index: 1000;
      width: 100%;
      display: flex;
      background: #fff;
      justify-content: space-between;
      align-items: center;
      padding: 10px;

      .order-count {
        margin-right: 10px;
      }

      .order-total {
        flex: 1;
        color: red;
      }

      .order-btn {
        width: 100px;
      }
    }
  }
</style>
